using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Sunny.UI;

public static class DomainAssembly
{
	public static Assembly CurrentAssembly()
	{
		return Assembly.GetExecutingAssembly();
	}

	public static string CurrentLocation()
	{
		return Assembly.GetExecutingAssembly().Location;
	}

	public static List<Assembly> GetUserAssemblies()
	{
		FileInfo fi = new FileInfo(CurrentLocation());
		return (from p in AppDomain.CurrentDomain.GetAssemblies()
			where p.Location.StartsWith(fi.DirectoryName)
			select p).ToList();
	}

	public static Type[] GetAssemblyTypes(this Assembly assembly, Type type)
	{
		try
		{
			return (from item in assembly.GetTypes()
				where !item.IsAbstract
				where type.IsAssignableFrom(item)
				select item).ToArray();
		}
		catch
		{
			return new Type[0];
		}
	}

	public static Type[] GetAssemblyTypes<T>(this Assembly assembly) where T : class
	{
		try
		{
			return (from item in assembly.GetTypes()
				where !item.IsAbstract
				where typeof(T).IsAssignableFrom(item)
				select item).ToArray();
		}
		catch
		{
			return new Type[0];
		}
	}

	public static T CreateInstance<T>(Type type)
	{
		return (T)Activator.CreateInstance(type);
	}
}
